﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DependencyPropertyTestDemo
{
    public class RangeTypeConverter : TypeConverter
    {
        /// <summary>
        /// 重写方法
        /// </summary>
        /// <param name="context">类型描述上下文</param>
        /// <param name="sourceType">源类型</param>
        /// <returns></returns>
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
                return true;
            return base.CanConvertFrom(context, sourceType);
        }

        /// <summary>
        /// 重写方法，从string的实例转换到Range的实例
        /// </summary>
        /// <param name="context">类型描述上下文</param>
        /// <param name="culture"></param>
        /// <param name="value">xaml传入的是一个string类型的参数</param>
        /// <returns></returns>
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            // 根据逗号分割
            string[] valueArray = value.ToString().Split('，');

            // 返回一个Range的实例
            if (valueArray.Length == 2)
                return new Range(int.Parse(valueArray[0]), int.Parse(valueArray[1]));

            return base.ConvertFrom(context, culture, value);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="destinationType"></param>
        /// <returns></returns>
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            var instance = context.Instance;

            return base.CanConvertTo(context, destinationType);
        }

        /// <summary>
        /// 重写方法，从Range的实例转换到string的实例
        /// </summary>
        /// <param name="context"></param>
        /// <param name="culture"></param>
        /// <param name="value"></param>
        /// <param name="destinationType"></param>
        /// <returns></returns>
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            return (value as Range).ToString();
            //return base.ConvertTo(context, culture, value, destinationType);
        }
    }
}
